<style scoped lang="scss">
.container {
  height: 100%;
  height: 100%;
  position: relative;
  .chart {
    height: 100%;
    height: 100%;
  }
  .legend_con {
    position: absolute;
    top: 40px;
    right: 20px;
    border: 1px solid #ddd;
    background: rgba(230, 230, 230, 0.8);
    z-index: 99;
    max-height: 220px;
    overflow-y: scroll;
    .legend_item_con {
      display: flex;
      align-items: center;
      padding: 5px;
      border: 1px solid #ccc;
      .legend_title {
        width: 110px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        font-size: 12px;
      }
      .legend_line_con {
        width: 70px;
        height: 8px;
        margin: 0 10px;
        border-radius: 3px;
      }
      .icon_button {
        margin: 0 4px;
        img {
          width: 20px;
          height: 20px;
          border-radius: 10px;
          cursor: pointer;
        }
      }
    }
    .legend_selected_con {
      background: rgba(24, 144, 255, 0.5);
    }
  }
}
</style>

<template>
  <div class="container">
    <div class="chart" ref="chart"></div>
    <div class="legend_con">
      <div
        :class="
          index === selectLineed
            ? 'legend_item_con legend_selected_con'
            : 'legend_item_con'
        "
        v-for="(item, index) in lineChartData"
        :key="index"
      >
        <div class="legend_title">{{ item.name }}</div>
        <div class="legend_line_con" :style="{ background: item.color }"></div>
        <div class="icon_button">
          <img :src="topIcon" @click.stop="moveUp(item, index)" alt="" />
        </div>
        <div class="icon_button">
          <img :src="downIcon" @click.stop="moveDown(item, index)" alt="" />
        </div>
        <div class="icon_button">
          <img
            :src="index === selectLineed ? selected : noSelected"
            @click.stop="selectLineFun(item, index)"
            alt=""
          />
        </div>
        <div class="icon_button">
          <img :src="deleteIcon" @click.stop="deleteLine(item, index)" alt="" />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import selected from "@/assets/images/manage/selected.png";
import noSelected from "@/assets/images/manage/noSelected.png";
import downIcon from "@/assets/images/manage/downIcon.png";
import topIcon from "@/assets/images/manage/topIcon.png";
import deleteIcon from "@/assets/images/manage/deleteIcon.png";
require("echarts/theme/macarons"); //  theme
import resize from "../../dashboard/mixins/resize";
import arrow_left_fill from "@/assets/images/dashboard/arrow_left_fill.png";
import arrow_right_fill from "@/assets/images/dashboard/arrow_right_fill.png";
import { parse } from "ol/expr/expression";
import { offset } from "ol/sphere";
var debounceTimer = null; //定时器 鼠标滚动防抖
let graphicData = [];
var xBigIdx = 0;
var startValue = []; //A线px的数据
var endValue = []; //B线px的数据
var alineData = {}; //a线x , y 用于计算显示ab线的长度衰耗等
var blineData = {}; //b线x , y 用于计算显示ab线的长度衰耗等
let startDist = []; //A线 value的数据
let endPoint = []; //B线value的数据
export default {
  mixins: [resize],
  props: {
    lineChartData: {
      type: Array,
      default: () => {
        return [];
      },
    },
    currentEvents: {
      type: Array,
      default: () => {
        return [];
      },
    },
    addType: {
      type: String,
      default: "",
    },
  },
  watch: {
    lineChartData: {
      handler(val) {
        let that = this;
        let arr = JSON.parse(JSON.stringify(val));
        that.chartChildData = arr;
        // console.log("that.chartChildData", that.chartChildData);
        // that.clearOption();
        that.$nextTick(() => {
          that.calcEchartData();
        });
      },
    },
  },
  data() {
    return {
      selected,
      noSelected,
      topIcon,
      downIcon,
      deleteIcon,
      chart: null,
      chartChildData: [], //echart的实际数据
      selectLineed: 0, //显示的哪一条曲线
      aLineLeft: 0, //a线
      bLineLeft: 0, //b线
      overAthousand: true, //x轴的显示 是否大于1000 , 大于是true
      midValPosi: 0, //缩放时候的中心点的点位 , 是a按钮的点位
      midBButtonPosi: 0, //点击b按钮的点位
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart();
    });
  },
  beforeDestroy() {
    this.disposeChart();
  },
  methods: {
    disposeChart() {
      if (!this.chart) {
        return;
      }
      this.chart.dispose();
      this.chart = null;
    },
    initChart() {
      let that = this;
      // that.chart = echarts.init(that.$el, "macarons");
      const chartDom = that.$refs.chart;
      that.chart = echarts.init(chartDom);
      that.$nextTick(() => {
        that.setOptions();
      });
    },
    calcEchartData() {
      //图形的数据
      let that = this;
      let midArr = [];
      let selected = {};
      if (that.chartChildData.length > 0) {
        for (let i = 0; i < that.chartChildData.length; i++) {
          let midObj = {
            id: that.chartChildData[i].name,
            name: that.chartChildData[i].name,
            type: "line",
            data: that.chartChildData[i].data,
            show: that.chartChildData[i].show,
            symbolSize: 1,
            symbol: "circle",
            smooth: true,
            showSymbol: false,
            itemStyle: {
              color: that.chartChildData[i].color,
              borderColor: that.chartChildData[i].color,
              textStyle: {
                color: that.chartChildData[i].color,
              },
            },
            lineStyle: {
              width: 1,
              color: that.chartChildData[i].color,
              shadowColor: "rgba(144, 255, 198, .3)",
            },
          };
          midArr.push(midObj);
          selected[that.chartChildData[i].name] = true;
        }
        for (let i = 0; i < that.chartChildData.length; i++) {
          //获取x轴最大值 , x轴显示最大值
          if (that.chartChildData[i + 1]) {
            if (
              that.chartChildData[i + 1].xData[
                that.chartChildData[i + 1].xData.length - 1
              ] >
              that.chartChildData[i].xData[
                that.chartChildData[i].xData.length - 1
              ]
            ) {
              xBigIdx = i + 1;
            }
          }
        }
        that.chart.setOption({
          legend: {
            selected,
          },
          series: midArr,
        });

        if (that.addType === "add") {
          that.graphicEvent();
        } else if (that.addType === "look") {
          that.graphicEvent();
        } else if (that.addType === "delete") {
          that.graphicEvent();
        }
        that.chart.on("dataZoom", function (params) {
          // 清除之前的计时器
          clearTimeout(debounceTimer);
          // 重新设置计时器，等待 200 毫秒后执行回调函数
          debounceTimer = setTimeout(function () {
            if (params?.start === 0 && params?.end === 100) {
              //说明是原始的缩放比例
              that.$parent.dataZoomFun(true);
            } else {
              //说明可以点击 返回原始比例缩放按钮
              that.$parent.dataZoomFun(false);
            }
            // 在这里执行你操作，更新 UI
            let start = params.start;
            let end = params.end;
            if (params.batch) {
              start = params?.batch[0]?.start;
              end = params?.batch[0]?.end;
            }
            that.getXposition(start, end); //
            that.graphicFun("zoom");
            that.graphicEvent("zoom");
          }, 150); // 200 毫秒的延迟
        });
      } else {
        that.clearOption();
      }
    },
    recoveryRatio() {
      //重置缩放比例
      this.chart.dispatchAction({
        type: "dataZoom",
        start: 0,
        end: 100,
        componentType: "dataZoom",
      });
    },
    clearOption() {
      let that = this;
      that.chart.clear();
      that.setOptions();
    },
    //转换在图形里, 一个单位值和一个px的转换 ,计算出graphics移动了多少
    convertPixel(x, y, type) {
      let that = this;
      var pointInData = [];
      let originValue = [];
      let targetValue = {};
      pointInData = that.chart.convertFromPixel({ seriesIndex: 0 }, [x, y]);
      originValue = that.chart.convertToPixel({ seriesIndex: 0 }, [
        pointInData[0],
        pointInData[1],
      ]);
      targetValue = that.chart.convertToPixel({ seriesIndex: 0 }, [
        pointInData[0],
        pointInData[1] + 1,
      ]);
      if (type === "top") {
        return originValue[1] - (originValue[1] - targetValue[1]);
      } else {
        return originValue[1] + (originValue[1] - targetValue[1]);
      }
    },
    //上移
    moveUp(item, index) {
      let that = this;
      // 更新数据
      item.data = item.data.map((value) => [
        value[0],
        value[1] + that.chartChildData[index].offset,
      ]);
      graphicData.forEach((element) => {
        if (element.id.split("&&")[1] == item.color) {
          if (element.y) {
            element.y = that.convertPixel(element.x, element.y, "top");
          } else if (element.shape) {
            element.shape.y1 = that.convertPixel(
              element.x,
              element.shape.y1,
              "top"
            );
            element.shape.y2 = that.convertPixel(
              element.x,
              element.shape.y2,
              "top"
            );
          } else {
            element.style.y = that.convertPixel(
              element.x,
              element.style.y,
              "top"
            );
          }
        }
      });
      // 更新图表
      that.chart.setOption({
        graphic: graphicData,
        series: {
          id: item.id,
          data: item.data,
        },
      });
    },
    moveDown(item, index) {
      //下移
      let that = this;
      // 更新数据
      item.data = item.data.map((value) => [
        value[0],
        value[1] - that.chartChildData[index].offset,
      ]);
      graphicData.forEach((element) => {
        if (element.id.split("&&")[1] == item.color) {
          if (element.y) {
            element.y = that.convertPixel(element.x, element.y, "bottom");
          } else if (element.shape) {
            element.shape.y1 = that.convertPixel(
              element.x,
              element.shape.y1,
              "bottom"
            );
            element.shape.y2 = that.convertPixel(
              element.x,
              element.shape.y2,
              "bottom"
            );
          } else {
            element.style.y = that.convertPixel(
              element.x,
              element.style.y,
              "bottom"
            );
          }
        }
      });
      // 更新图表
      that.chart.setOption({
        graphic: graphicData,
        series: {
          id: item.id,
          data: item.data,
        },
      });
    },
    selectLineFun(item, index) {
      //选择了哪条曲线
      this.selectLineed = index;
      this.$parent.selectLineFun(index);
      this.setABlineFun("first");
      this.graphicFun("first");
    },
    //计算点击b按钮后 b线的位置
    calcBLinePosiFun(startpercentPoint, endpercentPoint) {
      //1 先计算出缩放后相邻点位的px差值,  2 在中心点的基础上加上a按钮和b按钮的px差值,
      // 3 然后确定b线的px值, 根据px值在赋值到b线上
      let that = this;
      //convertToPixel
      let xData = that.chartChildData[xBigIdx].xData;
      let point1 = that.chart.convertToPixel(
        { seriesIndex: 0 }, // 指定系列索引
        [xData[startpercentPoint], 0] // 只需要提供 X 轴值，Y 轴值可以为 null
      );
      let point2 = that.chart.convertToPixel(
        { seriesIndex: 0 }, // 指定系列索引
        [xData[startpercentPoint + 1], 0] // 只需要提供 X 轴值，Y 轴值可以为 null
      );
      let pointDifference = parseInt(61 / (point2[0] - point1[0]));
      that.midBButtonPosi = that.midValPosi + pointDifference;
    },
    //放大缩小之后, 可以获取到 起点和终点的百分比 , 根据百分比计算出起点和终点
    getXposition(start, end) {
      let that = this;
      let length = that.chartChildData[xBigIdx].xData.length;
      let startpercentPoint = Math.floor((start / 100) * length);
      let endpercentPoint = Math.floor((end / 100) * length);
      let startPosiont = that.chartChildData[xBigIdx].xData[startpercentPoint];
      let endPosiont = that.chartChildData[xBigIdx].xData[endpercentPoint - 1];
      let midPercentPoint = (start + end) / 2;
      that.midValPosi = Math.floor((midPercentPoint / 100) * length);
      that.calcBLinePosiFun(startpercentPoint, endpercentPoint);
      // 需要计算 整个x轴的距离, 如果小于一公里, 就需要显示m, 否则显示km
      let subtractionValue = endPosiont - startPosiont;
      if (subtractionValue - 1000 > 0) {
        that.startFun();
      } else {
        that.overAthousand = false;
        that.chart.setOption({
          xAxis: [
            {
              axisLabel: {
                formatter: function (value) {
                  let strVal = value + " ";
                  let showText = "";
                  let midStr = strVal?.split(".");
                  showText = midStr[0];
                  return showText + "m";
                },
                splitNumber: 10,
              },
            },
          ],
        });
      }
      //需要设置A B两个按钮, 如果缩放图表之后, A或者B线不在图标显示范围内 , 就需要显示对应的按钮, 然后点击按钮后,可以显示对应的线
      if (blineData.x > alineData.x) {
        //B线在A线的右侧
        if (alineData.x < endPosiont && alineData.x >= startPosiont) {
          //A线在范围内
          that.$parent.ablineFun("a", true);
        } else {
          //A线不在范围内
          that.$parent.ablineFun("a", false);
        }
        if (blineData.x < endPosiont && blineData.x >= startPosiont) {
          //B线在范围内
          that.$parent.ablineFun("b", true);
        } else {
          //B线不在范围内
          that.$parent.ablineFun("b", false);
        }
      } else if (blineData.x === alineData.x) {
        //两线在一起
      } else {
        //B线在A线左侧
        if (alineData.x < startPosiont && alineData.x >= endPosiont) {
          //A线在范围内
          that.$parent.ablineFun("a", true);
        } else {
          //A线不在范围内
          that.$parent.ablineFun("a", false);
        }
        if (blineData.x < startPosiont && blineData.x >= endPosiont) {
          //B线在范围内
          that.$parent.ablineFun("b", true);
        } else {
          ///B线不在范围内
          that.$parent.ablineFun("b", false);
        }
      }
    },
    //需要重新赋值 ab线显示的文字
    startFun() {
      let that = this;
      that.overAthousand = true;
      that.chart.setOption({
        xAxis: [
          {
            axisLabel: {
              formatter: function (value) {
                var intValue = Math.round(value);
                let showVal = 0;
                showVal = intValue;
                let showText = "";
                if (showVal > 1000) {
                  showText = showVal / 1000 + "km";
                } else {
                  showText = showVal + "m";
                }
                return showText;
              },
              splitNumber: 40,
              // interval: 600, // 显示的标签
            },
          },
        ],
      });
    },
    deleteLine(item, index) {
      //删除曲线
      let that = this;
      that.chart.dispatchAction({
        type: "legendUnSelect",
        name: item.name,
      });
      //删除曲线上的标记, 就是graphic
      for (let i = 0; i < graphicData.length; i++) {
        if (graphicData[i].id.split("&&")[1] == item.color) {
          //隐藏标记
          graphicData[i].invisible = true;
        }
      }
      // 更新图表
      that.chart.setOption({
        graphic: graphicData,
      });
      for (let i = 0; i < graphicData.length; i++) {
        if (graphicData[i].id.split("&&")[1] == item.color) {
          //删除标记
          graphicData.splice(i, 1);
          i--;
        }
      }
      that.$parent.deleteLine(index);
    },
    setOptions() {
      let that = this;
      let series = [];
      that.chart.setOption(
        {
          backgroundColor: "#fff", // 例如：浅灰色
          legend: {
            show: false,
            // icon: "circle",
            // top: "5%",
            // right: "5%",
            // itemWidth: 6,
            // itemGap: 5,
            // textStyle: {
            //   // color: "#f40",
            //   padding: [3, 0, 0, 0],
            // },
          },
          tooltip: {
            show: false,
            // trigger: "axis",
          },
          xAxis: {
            name: "长度",
            type: "value",
            // data: [],
            axisLabel: {
              formatter: function (value) {
                var intValue = Math.round(value);
                let showVal = 0;
                // if (value && value != "0" && value.length > 0) {
                //   showVal = intValue?.toFixed(0);
                // }
                showVal = intValue;
                let showText = "";
                if (showVal > 1000) {
                  showText = showVal / 1000 + "km";
                } else {
                  showText = showVal + "m";
                }
                return showText;
              },
              splitNumber: 40,
              // interval: 40, // 显示的标签
            },
            splitLine: {
              show: true, // 显示 X 轴的分割线
              lineStyle: {
                color: "#dfe6ec", // 分割线颜色
                width: 1,
                type: "dashed", // 分割线类型（实线或虚线）
              },
            },
            axisLine: {
              show: true, // 显示 Y 轴线
              lineStyle: {
                color: "#333", // Y 轴线的颜色
                width: 1, // Y 轴线的宽度
                type: "solid", // Y 轴线的类型（实线或虚线）
              },
            },
          },
          yAxis: {
            axisTick: {
              show: false,
            },
            axisLine: {
              show: true, // 显示 Y 轴线
              lineStyle: {
                color: "#333", // Y 轴线的颜色
                width: 1, // Y 轴线的宽度
                type: "solid", // Y 轴线的类型（实线或虚线）
              },
            },
            interval: 5,
            splitArea: false,
            type: "value",
            min: 0,
            max: 80,
            splitLine: {
              show: true, // 显示 Y 轴的分割线
              lineStyle: {
                color: "#dfe6ec", // 分割线颜色
                width: 1,
                type: "dashed", // 分割线类型（实线或虚线）
              },
            },
          },
          grid: {
            left: 10,
            right: 10,
            bottom: 20,
            top: 30,
            containLabel: true,
          },
          dataZoom: [
            {
              type: "inside", // 内置型 dataZoom
              minSpan: 1, // 最小缩放范围为 10%
              // maxSpan: 97, // 最大缩放范围为 80%
            },
          ],
          tooltip: {
            show: false,
          },
          series: [
            {
              name: "",
              // symbol: "none",
              type: "line",
              data: series,
            },
          ],
        },
        true
      );
    },
    calcxPoistion(x) {
      //由于x用的是实际的value,所以需要计算x的位置
      return parseFloat(x) * 1000;
    },
    calcDist(type) {
      //计算起点和终点的点位
      let that = this;
      let startCalcDist = null;
      let endCalcPoint = null;
      let midArr = that.currentEvents[that.selectLineed];
      for (let i = 0; i < midArr.length; i++) {
        if (midArr[i].type === 1) {
          //是起点
          startCalcDist = [
            that.calcxPoistion(midArr[i].startDist),
            midArr[i].startLevel,
          ];
        }
        if (midArr[i].type === 2) {
          //是终点
          endCalcPoint = [
            that.calcxPoistion(midArr[i].startDist),
            midArr[i].startLevel,
          ];
        }
      }
      if (type === 1) {
        return startCalcDist;
      } else {
        return endCalcPoint;
      }
    },
    //graphic 制作事件 图表
    graphicEvent(type) {
      let that = this;
      let graphic = [];
      that.currentEvents.forEach((tableData) => {
        tableData.map((item, index) => {
          let showValue = [];
          showValue = that.chart.convertToPixel(
            { seriesIndex: 0 }, // 指定系列索引
            [that.calcxPoistion(item.startDist), item.startLevel] // 只需要提供 X 轴值，Y 轴值可以为 null
          );
          if (item.type == 1) {
            graphic.push({
              id: "image-start-top-" + index + "&&" + tableData[0].color,
              type: "image", // 使用 image 元素
              invisible: false,
              style: {
                image: arrow_right_fill, // 图像的 URL
                width: 24, // 图像宽度
                height: 24, // 图像高度
                opacity: 1, // 透明度
                rotation: Math.PI / 4, // 旋转 45 度 (π/4 弧度)
              },
              x: showValue[0] - 4,
              y: showValue[1] - 22,
              z: 100, // 图层层级，确保图像位于其他元素之上
            });
            graphic.push({
              id: "image-start-bottom-" + index + "&&" + tableData[0].color,
              type: "image", // 使用 image 元素
              invisible: false,
              style: {
                image: arrow_right_fill, // 图像的 URL
                width: 24, // 图像宽度
                height: 24, // 图像高度
                opacity: 1, // 透明度
                rotation: Math.PI / 4, // 旋转 45 度 (π/4 弧度)
              },
              // position: ["50%", "50%"], // 将图像放置在图表的中心
              x: showValue[0] - 4,
              y: showValue[1] - 2,
              z: 100, // 图层层级，确保图像位于其他元素之上
            });
          } else if (item.type == 2) {
            graphic.push({
              id: "image-end-top-" + index + "&&" + tableData[0].color,
              type: "image", // 使用 image 元素
              invisible: false,
              style: {
                image: arrow_left_fill, // 图像的 URL
                width: 24, // 图像宽度
                height: 24, // 图像高度
                opacity: 1, // 透明度
                rotation: Math.PI / 4, // 旋转 45 度 (π/4 弧度)
              },
              // position: ["50%", "50%"], // 将图像放置在图表的中心
              x: showValue[0] - 20,
              y: showValue[1] - 2,
              z: 100, // 图层层级，确保图像位于其他元素之上
            });
            graphic.push({
              id: "image-end-bottom-" + index + "&&" + tableData[0].color,
              type: "image", // 使用 image 元素
              invisible: false,
              style: {
                image: arrow_left_fill, // 图像的 URL
                width: 24, // 图像宽度
                height: 24, // 图像高度
                opacity: 1, // 透明度
                rotation: Math.PI / 4, // 旋转 45 度 (π/4 弧度)
              },
              // position: ["50%", "50%"], // 将图像放置在图表的中心
              x: showValue[0] - 20,
              y: showValue[1] - 22,
              z: 100, // 图层层级，确保图像位于其他元素之上
            });
          }
          graphic.push({
            id: "line-line_" + index + "&&" + tableData[0].color,
            type: "line",
            x: showValue[0],
            invisible: false,
            textConfig: {
              position: "top",
              inside: true,
            },
            shape: {
              y1: showValue[1] + 10,
              y2: showValue[1] - 10, // 使用像素坐标
            },
            style: {
              stroke: "#f40",
              lineWidth: 1,
            },
          });
          graphic.push({
            id: "line-text_" + index + "&&" + tableData[0].color,
            type: "text",
            x: showValue[0],
            invisible: false,
            style: {
              text: item.index, // 要显示的文字
              y: showValue[1] - 20, // 文字的 y 坐标，设置为圆心的 y 坐标
              // textAlign: "center", // 文字水平居中
              textVerticalAlign: "middle", // 文字垂直居中
              // fill: "#f10", // 文字颜色
              fill: tableData[0].color,
              font: "13px Arial", // 文字字体和大小
            },
          });
        });
      });
      graphic.forEach((element) => {
        graphicData.forEach((item) => {
          if (element.id == item.id) {
            if (element.y) {
              element.y = item.y;
            } else if (element.shape) {
              element.shape.y1 = item.shape.y1;
              element.shape.y2 = item.shape.y2;
            } else {
              element.style.y = item.style.y;
            }
          }
        });
      });
      that.chart.setOption({
        graphic,
      });
      that.graphicFun(type || "first"); //制作AB线
    },
    //graphic 制作  AB线
    graphicFun(type) {
      let that = this;
      const graphic = [];
      let arrMid = [1, 2];
      if (type === "first") {
        startDist = that.calcDist(1);
        endPoint = that.calcDist(2);
      }
      if (type === "a" || type === "b") {
        //根据a b 调整线的位置
        let data = that.chartChildData[that.selectLineed].data;
        let midval = data[that.midValPosi];
        if (type === "a") {
          startDist = [midval[0], midval[1]];
        } else {
          midval = data[that.midBButtonPosi];
          endPoint = [midval[0], midval[1]];
        }
      }
      if (type === "zoom") {
        startDist = [alineData.x, alineData.y];
        endPoint = [blineData.x, blineData.y];
      }
      startValue = that.chart.convertToPixel({ seriesIndex: 0 }, startDist);
      endValue = that.chart.convertToPixel({ seriesIndex: 0 }, endPoint);
      that.aLineLeft = startValue[0];
      that.bLineLeft = endValue[0];
      arrMid.map((item, index) => {
        graphic.push({
          type: "group",
          id: index + "-group",
          x: index === 1 ? startValue[0] : endValue[0],
          children: [
            {
              id: "line-" + index,
              type: "line",
              cursor: "move",
              textConfig: {
                position: "top",
                inside: true,
              },
              shape: {
                y1: 30,
                y2: that.chart.getHeight() - 30 - 10, // 使用像素坐标
              },
              style: {
                stroke: "#000",
                lineWidth: 1,
              },
            },
            {
              type: "circle",
              id: "circleMarker-" + index,
              top: index === 1 ? 80 : 130,
              cursor: "move",
              shape: {
                r: 18,
              },
              style: {
                fill: "#298CC4", // 不填充颜色
                stroke: index === 1 ? "#298CC4" : "#298CC4", // 边框颜色
                lineWidth: 2, // 边框宽度
              },
            },
            {
              type: "text",
              id: "text-" + index,
              style: {
                text: index === 1 ? "A" : "B", // 要显示的文字
                y: index === 1 ? 100 : 150, // 文字的 y 坐标，设置为圆心的 y 坐标
                textAlign: "center", // 文字水平居中
                textVerticalAlign: "middle", // 文字垂直居中
                fill: "#fff", // 文字颜色
                font: "16px Arial", // 文字字体和大小
              },
            },
            {
              id: "rect-" + index,
              type: "rect", // 创建背景矩形
              shape: {
                width: 100,
                height: 40,
              },
              style: {
                fill: "rgba(0,0,0,0.7)", // 背景颜色
                stroke: "#000", // 边框颜色
                lineWidth: 1,
              },
              y: index === 1 ? 30 : 80, // 文字的 y 坐标，设置为圆心的 y 坐标
              left: "center", // 初始位置
              z: 100, // 确保矩形位于最上层
            },
            {
              id: "rect-text-top-" + index,
              type: "text", // 创建文本
              style: {
                text: "", // 初始文本为空
                fontSize: 13,
                fill: "#fff", // 文字颜色
                textAlign: "left", // 文字水平居中
                textVerticalAlign: "middle", // 文字垂直居中
                textBaseline: "top", // 基线对齐方式
              },
              left: -45, // 文本居中
              y: index === 1 ? 50 - 9 : 100 - 9, // 文字的 y 坐标，设置为圆心的 y 坐标
              z: 101, // 确保文本位于矩形之上
            },
            {
              id: "rect-text-bottom-" + index,
              type: "text", // 创建文本
              style: {
                text: "", // 初始文本为空
                fontSize: 13,
                fill: "#fff", // 文字颜色
                textAlign: "left", // 文字水平居中
                textVerticalAlign: "middle", // 文字垂直居中
                textBaseline: "top", // 基线对齐方式
              },
              left: -45, // 文本居中
              y: index === 1 ? 50 + 9 : 100 + 9, // 文字的 y 坐标，设置为圆心的 y 坐标
              z: 101, // 确保文本位于矩形之上
            },
          ],
          draggable: true, // 设置整个group可拖拽
          ondrag: function (params, event) {
            that.limitedRegionMove(params, index);
            // 直接在画布坐标系上进行操作，不需要转换
            // params.target.shape.x1 = params.target.shape.x2 = params.offsetX;
            // that.chart.setOption({ graphic });
          },
          ondragend: function (params, event) {
            that.onDragend(index, params);
          },
        });
      });
      setTimeout(() => {
        that.pointDataFun(
          that.aLineLeft < 0 ? 0 : that.aLineLeft,
          startValue[1] < 0 ? 0 : startValue[1],
          1
        );
        that.pointDataFun(
          that.bLineLeft < 0 ? 0 : that.bLineLeft,
          endValue[1] < 0 ? 0 : endValue[1],
          0
        );
        // that.pointDataFun(that.aLineLeft, startValue[1], 1);
        // that.pointDataFun(that.bLineLeft, endValue[1], 0);
      }, 50);
      let option = that.chart.getOption();
      graphicData = option.graphic[0].elements;
      that.chart.setOption({
        graphic,
      });
    },
    posiLineFun(type) {
      //点击 a  b  按钮
      let that = this;
      if (type === "a") {
        this.graphicFun("a");
        this.setABlineFun("a");
      } else if (type === "b") {
        this.graphicFun("b");
        this.setABlineFun("b");
      }
    },
    //计算 确定a b线位置的计算
    confirmABPosiCalcFun() {},
    setABlineFun(type) {
      //切换曲线的时候, 需要重新计算a,b线的位置
      //如果startPoint变了, 就换算a线的px值
      //如果endPoint变了, 就换算b线的px值
      let that = this;
      if (type === "first") {
        startDist = that.calcDist(1);
        endPoint = that.calcDist(2);
      }
      if (type === "a" || type === "b") {
        //根据a b 调整线的位置
        let data = that.chartChildData[that.selectLineed].data;
        let midval = data[that.midValPosi];
        if (type === "a") {
          startDist = [midval[0], midval[1]];
        } else {
          midval = data[that.midBButtonPosi];
          endPoint = [midval[0], midval[1]];
        }
      }
      startValue = that.chart.convertToPixel({ seriesIndex: 0 }, startDist);
      setTimeout(() => {
        that.pointDataFun(
          startValue[0] < 0 ? 0 : startValue[0],
          startValue[1] < 0 ? 0 : startValue[1],
          1
        );
      }, 50);
      //说明状态已经是el, end节点已经获取
      endValue = that.chart.convertToPixel({ seriesIndex: 0 }, endPoint);
      setTimeout(() => {
        that.pointDataFun(
          endValue[0] < 0 ? 0 : endValue[0],
          endValue[1] < 0 ? 0 : endValue[1],
          0
        );
      }, 50);
    },
    pointDataFun(x, y, index) {
      // 将像素坐标转换为数据坐标 , 然后展示出 当前的x 和 y的 文字值
      let that = this;
      var pointInData = that.chart.convertFromPixel({ seriesIndex: 0 }, [x, y]);
      let showXtext = pointInData[0];
      let showYtext = pointInData[1];
      let midArr = that.chartChildData[that.selectLineed].data;
      let valueX = that.findClosestValueSorted(pointInData[0]);
      for (let i = 0; i < midArr.length; i++) {
        if (midArr[i][0] === valueX) {
          showYtext = midArr[i][1];
        }
      }
      //index 是1 是A线  ;  0是B线
      if (index === 1) {
        alineData.x = showXtext;
        alineData.y = showYtext;
      } else {
        blineData.x = showXtext;
        blineData.y = showYtext;
      }
      that.$parent.abCalcFun(alineData, blineData);
      let graphic = {};
      if (index === 1) {
        //是A线
        graphic = [
          {
            id: "rect-text-top-1",
            style: {
              text: `x: ${that.showTextFun(showXtext) || 0}`,
            },
          },
          {
            id: "rect-text-bottom-1",
            style: {
              text: `y: ${showYtext ? that.fixFun(showYtext) : 0}dB`,
            },
          },
        ];
      } else {
        graphic = [
          {
            id: "rect-text-top-0",
            style: {
              text: `x: ${that.showTextFun(showXtext) || 0}`,
            },
          },
          {
            id: "rect-text-bottom-0",
            style: {
              text: `y: ${showYtext ? that.fixFun(showYtext) : 0}dB`,
            },
          },
        ];
      }
      that.chart.setOption({ graphic });
    },
    showTextFun(e) {
      //显示 a b的文字
      let showNum = 0;
      if (e == 0) {
        return 0 + "m";
      } else if (!e) {
        return (e?.toFixed(2) || 0) + "m";
      } else if (!this.overAthousand) {
        //小于1000
        return (e?.toFixed(2) || 0) + "m";
      } else {
        //大于1000
        showNum = e / 1000;
        return (showNum?.toFixed(3) || 0) + "km";
      }
    },
    // 拖拽完渲染
    onDragend(index, param) {
      let that = this;
      let letfX = param.offsetX;
      let id = param.target.id; //获取游标的id
      let minX = that.getGridDistance("left");
      let gridWidth = that.chart.getWidth();
      let maxX = gridWidth - that.getGridDistance("right");
      if (letfX <= minX) {
        letfX = minX;
      }
      if (letfX >= maxX) {
        letfX = maxX;
      }
      let graphic = {
        id: id,
        x: letfX,
      };
      that.chart.setOption({ graphic });
      var xValue = that.convertFromPixel(param.offsetX);
      if (param.offsetX <= minX) {
        //如果 小于了最小值, 出了边框
        xValue = that.convertFromPixel(minX);
      }
      if (param.offsetX >= maxX) {
        //如果大于了 最大值,  出了边框
        xValue = that.convertFromPixel(maxX);
      }
      //index  1是A   0是B
      let gridBottom = that.getGridDistance("bottom");
      let length = that.chartChildData[that.selectLineed].xData.length;
      let currentXdataMax =
        that.chartChildData[that.selectLineed].xData[length - 1];
      var pointInData = that.chart.convertFromPixel({ seriesIndex: 0 }, [
        param.offsetX,
        null,
      ]);
      if (pointInData[0] >= currentXdataMax) {
        let midLen = that.chart.convertToPixel({ seriesIndex: 0 }, [
          currentXdataMax,
          null,
        ]);
        let graphic = {
          id: id,
          x: midLen[0],
          bottom: gridBottom,
        };
        that.chart.setOption({ graphic });
        return;
      }
    },
    //grid距离边界的距离
    getGridDistance: function (direction) {
      let grid = this.chart.getOption().grid[0],
        gridWidth = this.chart.getWidth(), //ECharts 实例容器的宽度
        gridHeight = this.chart.getHeight(), //ECharts 实例容器的高度
        distance = 0;

      //若是百分数长度转化成数值型长度
      //由于线宽的影响，计算游标位置时将游标位置向左偏移2px，向下偏移2px
      switch (direction) {
        case "left":
          // distance = grid.left; //grid距离左边边界的距离
          // let index = distance.toString().indexOf("%");
          // distance =
          //   index == -1
          //     ? distance - 2
          //     : (distance.substring(0, index) * gridWidth) / 100 - 2;
          distance = 31;
          break;
        case "right":
          distance = grid.right; //grid距离右边边界的距离
          let indexr = distance.toString().indexOf("%");
          distance =
            indexr == -1
              ? distance + 2
              : (distance.substring(0, indexr) * gridWidth) / 100 + 2;
          break;
        case "top":
          distance = grid.top;
          let indext = distance.toString().indexOf("%");
          distance =
            indext == -1
              ? distance + 2
              : (distance.substring(0, indext) * gridHeight) / 100 + 2;
          break;
        case "bottom":
          distance = 38;
          break;
        default:
          console.log("default grid距离边界的距离");
          break;
      }
      return distance;
    },
    //限制鼠标移动区域 , 也是拖拽函数
    limitedRegionMove: function (e, index) {
      //index  1是A   0是B
      //获取 AB线的 位置      // 从配置项中获取graphic组件的信息
      let that = this;
      let x = e.offsetX,
        y = e.offsetY,
        letfX = x,
        gridWidth = that.chart.getWidth(),
        minX = that.getGridDistance("left"),
        maxX = gridWidth - that.getGridDistance("right"),
        gridBottom = that.getGridDistance("bottom");
      let id = e.target.id; //获取游标的id
      let tempY = 0; //临时存放y值
      let length = that.chartChildData[that.selectLineed].xData.length;
      let currentXdataMax =
        that.chartChildData[that.selectLineed].xData[length - 1];
      var pointInData = that.chart.convertFromPixel({ seriesIndex: 0 }, [x, y]);
      if (pointInData[0] >= currentXdataMax) {
        let midLen = that.chart.convertToPixel({ seriesIndex: 0 }, [
          currentXdataMax,
          null,
        ]);
        let graphic = {
          id: id,
          x: midLen[0],
          bottom: gridBottom,
        };
        that.chart.setOption({ graphic });
        return;
      }
      if (letfX <= minX) {
        letfX = minX;
      }
      if (index === 0) {
        //移动的是B线
        that.bLineLeft = letfX;
      }
      if (index === 1) {
        //移动的是a线
        that.aLineLeft = letfX;
      }
      //展示当前的x 和 y的值 , 在AB线 上显示
      that.pointDataFun(x < 0 ? 0 : x, y < 0 ? 0 : y, index);
      //上下不允许拖动，左右设定移动范围
      if (x <= minX || x > maxX || Math.abs(y - tempY) > 0) {
        tempY = y; //鼠标拖动前一次y轴值
        if (x <= minX) {
          letfX = minX;
        } else if (x > maxX) {
          letfX = maxX;
        }
        let graphic = {
          id: id,
          x: letfX,
          bottom: gridBottom,
        };
        that.chart.setOption({ graphic });
      }
      if (index === 1) {
        //要根据拖动  与地图联动
      }
    },
    findClosestValueSorted(target) {
      //获取与x值最近的值, 从而获取到y值
      let that = this;
      let arr = that.chartChildData[that.selectLineed].data;
      if (!arr || arr.length === 0) return null; // 如果数组为空，返回 null
      let start = 0;
      let end = arr.length - 1;
      // console.log("================", arr);
      // 二分查找
      while (start <= end) {
        const mid = Math.floor((start + end) / 2);
        if (arr[mid][0] === target) {
          return arr[mid][0]; // 如果找到了目标值，直接返回
        } else if (arr[mid][0] < target) {
          start = mid + 1;
        } else {
          end = mid - 1;
        }
      }
      // 检查最近的两个候选值
      const closestStart = arr[end][0];
      const closestEnd = arr[start][0];
      // 返回与目标值最接近的值
      if (end >= 0 && start < arr.length) {
        return Math.abs(target - closestStart) <= Math.abs(closestEnd - target)
          ? closestStart
          : closestEnd;
      } else if (end >= 0) {
        return closestStart;
      } else {
        return closestEnd;
      }
    },
    convertFromPixel(offsetX) {
      //根据x的left值,  , 计算是x轴上的第多少个点位
      var xValue = this.chart.convertFromPixel({ seriesIndex: 0 }, [
        offsetX,
        0,
      ]);
      return xValue[0];
    },
    fixFun(e, type) {
      if (!e && type === "blank") {
        return "";
      } else if (!e && e != 0) {
        return "-";
      } else if (e == 0) {
        return e;
      } else if (e == "-") {
        return "-";
      } else if (e == "null") {
        return "-";
      } else if (e == "-null") {
        return "-";
      } else {
        let num = parseFloat(e);
        let strData = num.toString();
        let splitData = strData.split(".");
        if (num % 1 === 0) {
          return num;
        } else if (splitData.length > 0) {
          if (splitData[1].length >= 4) {
            return parseFloat(num.toFixed(4));
          } else if (splitData[1].length === 3) {
            return parseFloat(num.toFixed(3));
          } else if (splitData[1].length === 2) {
            return parseFloat(num.toFixed(2));
          } else if (splitData[1].length === 1) {
            return parseFloat(num.toFixed(1));
          } else {
            return parseFloat(num);
          }
        } else {
          return num;
        }
      }
    },
  },
};
</script>
